<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
		<title>输入提示后查询</title>
		<link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css" />
		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	</head>
	<body onload="driver();">
		<div id="container"></div>
		<div id="myPageTop" style="height: 150px;width: 150px;">
			<table>
				<tr>
					<td>
						<label>请输入上车地点：</label>
					</td>
				</tr>
				<tr>
					<td>
						<input id="tipinput1" style="width: 145px;" />
					</td>
				</tr>
				<tr>
					<td>
						<label>请输入目的地：</label>
					</td>
				</tr>
				<tr>
					<td>
						<input id="tipinput2" style="width: 145px;" />
					</td>
				</tr>
				<tr>
					<td>
						<button onclick="getFromAndTo()">查看路线</button>
						<button onclick="dispatch()">开始打车</button>
					</td>
				</tr>


				<tr>
					<td>
						<select id="rankSelect">

						</select>
					</td>
				</tr>
			</table>
			<div id="panel"></div>

		</div>

		<script type="text/javascript">
			window._AMapSecurityConfig = {
				securityJsCode: '7b661f2d5cff79b13627ca4a9482791a'
			}
		</script>
		<script src="js/jquery-1.10.2.min.js"></script>
		<script src="/utils/request.js"></script>
		<script src="https://webapi.amap.com/maps?v=2.0&key=0df775699078245259de51e2bef634d8&plugin=AMap.PolygonEditor">
		</script>

		<script src="https://webapi.amap.com/maps?v=1.4.15&key=0df775699078245259de51e2bef634d8&plugin=Map3D"></script>
		<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=0df775699078245259de51e2bef634d8">
		</script>
		<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=0df775699078245259de51e2bef634d8">
		</script>
		<script type="text/javascript"
			src="https://webapi.amap.com/maps?v=2.0&key=0df775699078245259de51e2bef634d8&plugin=AMap.Driving"></script>
		<script type="text/javascript">
			//地图加载
			var map = new AMap.Map("container", {
				resizeEnable: true,
				center: [116.397428, 39.90923], //地图中心点
				zoom: 13, //地图显示的缩放级别


			});
			//输入提示
			var autoOptions1 = {
				input: "tipinput1"
			};
			var autoOptions2 = {
				input: "tipinput2"
			};

			var startplace;
			var startlongitude;
			var startlatitude;
			var endplace;
			var endlongitude;
			var endlatitude;


			AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function() {
				var auto = new AMap.AutoComplete(autoOptions1);
				var placeSearch = new AMap.PlaceSearch({
					map: map
				}); //构造地点查询类
				auto.on("select", select); //注册监听，当选中某条记录时会触发
				function select(e) {
					placeSearch.setCity(e.poi.adcode);
					placeSearch.search(e.poi.name); //关键字查询查询
					console.log("arguments23")
					console.log(e);
					startplace = e.poi.name;
					startlongitude = e.poi.location.lng;
					startlatitude = e.poi.location.lat;
					console.log("起点地址：" + startplace)
					console.log("起点经度：" + startlongitude)
					console.log("起点纬度：" + startlatitude)

				}
			});
			AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function() {
				var auto = new AMap.AutoComplete(autoOptions2);
				var placeSearch = new AMap.PlaceSearch({
					map: map
				}); //构造地点查询类
				auto.on("select", select); //注册监听，当选中某条记录时会触发
				function select(e) {
					placeSearch.setCity(e.poi.adcode);
					placeSearch.search(e.poi.name); //关键字查询查询
					console.log(e);
					endplace = e.poi.name;
					endlongitude = e.poi.location.lng;
					endlatitude = e.poi.location.lat;
					console.log("终点地址：" + endplace)
					console.log("终点经度：" + endlongitude)
					console.log("终点纬度：" + endlatitude)
				}
			});
			var element1 = document.getElementById('tipinput1');
			let input1 = element1.value;
			var element2 = document.getElementById('tipinput2');
			let input2 = element2.value;
			test = () => {
				var test = document.getElementById('rankSelect');

				var selectedValue = test.value;
				console.log(selectedValue)

			}
			getFromAndTo = () => {

				var element1 = document.getElementById('tipinput1');
				let input1 = element1.value;
				var element2 = document.getElementById('tipinput2');
				let input2 = element2.value;
				console.log('input1:' + input1, 'input2:' + input2);
				var driving = new AMap.Driving({
					map: map,
					// panel: "panel"
				});
				// 根据起终点名称规划驾车导航路线
				driving.search([{
						keyword: input1,
						city: '北京'
					},
					{
						keyword: input2,
						city: '北京'
					}
				], function(status, result) {
					// result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
					if (status === 'complete') {
						console.log(result)
						orderKm = result.routes[0].distance;
						let luxian = parseRouteToPath(result.routes[0])
						// AMap.plugin('AMap.MoveAnimation', function() {

						// 	let marker = new AMap.Marker({
						// 		map: map,
						// 		position: luxian[0],
						// 		icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
						// 		offset: new AMap.Pixel(-13, -26),
						// 	});

						// 	// 绘制轨迹
						// 	var polyline = new AMap.Polyline({
						// 		map: map,
						// 		path: luxian,
						// 		showDir: true,
						// 		strokeColor: "#28F", //线颜色
						// 		// strokeOpacity: 1,     //线透明度
						// 		strokeWeight: 6, //线宽
						// 		// strokeStyle: "solid"  //线样式
						// 	});

						// 	var passedPolyline = new AMap.Polyline({
						// 		map: map,
						// 		strokeColor: "#AF5", //线颜色
						// 		strokeWeight: 6, //线宽
						// 	});


						// 	marker.on('moving', function(e) {
						// 		passedPolyline.setPath(e.passedPath);
						// 		// map.setCenter(e.target.getPosition(), true)
						// 	});
						// 	map.setFitView();
						// 	marker.moveAlong(luxian, {
						// 		// 每一段的时长
						// 		duration: 500, //可根据实际采集时间间隔设置
						// 		// JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
						// 		autoRotation: true,
						// 	});
						// });
						console.log(orderKm)
					} else {
						console.log('获取驾车数据失败：' + result)
					}
				});
			}
			dispatch = () => {
				let jkl = window.location.search + "";
				let token = jkl.substring(1);
				console.log(input1, input2);
				let message = { //群聊
					to: 'all',
					content: 'hello' + input1 + "==" + input2
				}
				if (message) {
					socket.send(JSON.stringify(message));
				}
				var test = document.getElementById('rankSelect');

				var rankId = test.value;
				var Order = {
					"startPlace": startplace,
					"startLongitude": startlongitude,
					"startLatitude": startlatitude,
					"endPlace": endplace,
					"endLongitude": endlongitude,
					"endLatitude": endlatitude,
					"orderKm": orderKm,
					"token": token,
					"rankId": rankId
				}
				$.ajax({
					url: '/api/order/order/judge',
					type: 'post',
					headers: {
						'Content-Type': 'application/json',
						"Authorization": "Bearer " + token,
					}, //设置请求头
					dataType: 'json',
					data: JSON.stringify(Order),
					success: function(data) {
						console.log(data)
						if (data.code == 200) {
							$.ajax({
								url: '/api/order/order/playOrder',
								type: 'post',
								headers: {
									'Content-Type': 'application/json',
									"Authorization": "Bearer " + token,
								}, //设置请求头
								dataType: 'json',
								data: JSON.stringify(Order),
								success: function(data) {
									console.log(data)
									if (data.success) {
										alert("下单成功")
										//下完单后刷新页面
									} else {
										alert(data.msg)
										//下完单后刷新页面
										window.location.reload();
									}
								},
								error: function(obj, msg, e) { //异常
									alert("网络异常请稍后再试")
									//下完单后刷新页面
									window.location.reload();
								}
							});
						} else {
							alert(data.msg)
						}
					},
					error: function(obj, msg, e) { //异常
						alert("后端异常请等待工作人员维修")
					}
				});
			}

			function cL() {
				var url = window.location.search + "";
				console.log(url.substring(1));
				// 1. 创建一个 WebSocket 对象
				socket = new WebSocket(`ws://127.0.0.1:18085/websocket/chat/${url.substring(1)}`);
				// 2. 监听 WebSocket 连接事件
				socket.addEventListener("open", function(event) {
					console.log("连接事件成功:", event);
				});
				// 3. 监听 WebSocket 收到消息事件
				socket.addEventListener("message", function(event) {
					console.log("接收到的消息事件:", event.data);
				});
				// 4. 监听 WebSocket 关闭事件
				socket.addEventListener("close", function(event) {
					console.log("出错了关闭WebSocket:", event);

				});
				// 5. 监听 WebSocket 出错事件
				socket.addEventListener("error", function(event) {
					console.error("WebSocket error报错:", event);
				});
			}
			// 6、webSocket发送消息
			function sendMessage() {}
			cL();
			AMap.plugin('AMap.Geolocation', function() {
				var geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 10000, //超过10秒后停止定位，默认：5s
					buttonPosition: 'RB', //定位按钮的停靠位置
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
				});
				map.addControl(geolocation);
				geolocation.getCurrentPosition(function(status, result) {
					if (status == 'complete') {
						onComplete(result)
					} else {
						onError(result)
					}
				});
			});
			//解析定位结果
			function onComplete(data) {
				let jkl = window.location.search + "";
				let token = jkl.substring(1);
				var str = [];
				str.push('定位结果：' + data.position);
				console.log(data.position.lat);
				var LocationData = {
					longitude: data.position.lng,
					latitude: data.position.lat
				}
				$.ajax({
					url: '/api/mymodule/demo1/saveLatitudeAndLongitude',
					type: 'post',
					headers: {
						'Content-Type': 'application/json',
						"Authorization": "Bearer " + token,
					}, //设置请求头
					dataType: 'json',
					data: JSON.stringify(LocationData),
					success: function(data) {
						console.log(data)
						if (data.msg == 200) {
							console.log("获取自身位置成功")
							//下完单后刷新页面
						} else {
							console.log(data.msg)
							//下完单后刷新页面
							// window.location.reload();
						}
					}
				});
				str.push('定位类别：' + data.location_type);
				if (data.accuracy) {
					str.push('精度：' + data.accuracy + ' 米');
				} //如为IP精确定位结果则没有精度信息
				str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
			}

			function driver() {
				let jkl = window.location.search + "";
				let token = jkl.substring(1);
				$.ajax({
					url: '/api/order/order/selthreedriver',
					type: 'post',
					headers: {
						'Content-Type': 'application/json',
						"Authorization": "Bearer " + token,
					}, //设置请求头
					dataType: 'json',
					success: function(data) {
						console.log(data.data)
						if (data.code == 200) {
							// alert("司机位置查询成功")
							//下完单后刷新页面
							data.data.forEach(function(point) {
								// 新的标记对象
								var newMarker = {
									icon: 'D:\\QQ下载\\RuoYi-App\\static\\images\\car\\white2.png',
									position: [point.x, point.y]
								};
								var viaMarker = new AMap.Marker({
									position: new AMap.LngLat(point.x, point.y),
									// 将一张图片的地址设置为 icon
									icon: '/static/images/car/white1.png',
									// 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
									offset: new AMap.Pixel(-200, -230)
								});

								// 将新的标记对象添加到 markers 数组中
								markers.push(newMarker);
								map.add([viaMarker]);

							});
							// console.log("markers" + markers[0].position)

						} else {
							console.log(data.msg)
							//下完单后刷新页面

						}
					},
					error: function(obj, msg, e) { //异常
						alert("网络异常请稍后再试")
						//下完单后刷新页面

					}
				});
				$.ajax({
					url: '/api/rank/rank/rankList',
					type: 'get',
					headers: {
						'Content-Type': 'application/json',
						"Authorization": "Bearer " + token,
					}, //设置请求头
					dataType: 'json',
					success: function(data) {
						console.log(data)
						if (data.code == 200) {
							console.log();
							const selectElement = document.getElementById('rankSelect');
							data.data.forEach(option => {
								const optionElement = document.createElement('option');
								optionElement.value = option.id;
								optionElement.textContent = option.rankName;
								selectElement.appendChild(optionElement);
							});
						} else {
							console.log(data.msg)
							//下完单后刷新页面

						}
					},
					error: function(obj, msg, e) { //异常
						alert("网络异常请稍后再试")
						//下完单后刷新页面

					}
				});

			}

			var markers = [];

			// 添加一些分布不均的点到地图上,地图上添加三个点标记，作为参照
			markers.forEach(function(marker) {
				new AMap.Marker({
					map: map,
					icon: marker.icon,
					position: [marker.position[0], marker.position[1]],
					offset: new AMap.Pixel(-13, -30)
				});
			});

			var center = map.getCenter();
			var centerText = '当前中心点坐标：' + center.getLng() + ',' + center.getLat();

			// // 添加事件监听, 使地图自适应显示到合适的范围
			// AMap.event.addDomListener(document.getElementById('setFitView'), 'click', function() {
			// 	var newCenter = map.setFitView();
			// });

			//获取起点和终点之间路线的坐标点
			function parseRouteToPath(route) {
				var path = []
				debugger
				for (var i = 0, l = route.steps.length; i < l; i++) {
					var step = route.steps[i]

					for (var j = 0, n = step.path.length; j < n; j++) {
						path.push([step.path[j].lng, step.path[j].lat])
					}
				}

				return path
			}
		</script>
	</body>
</html>